<template>
  <van-popup
    v-model:show="props.visibleCity"
    position="bottom"
    :overlay="true"
  >
    <van-picker
      ref="pickers"
      :columns="Category"
      cancel-button-text="清除选择"
      @change="onChange"
      value-key="Category"
      @confirm="onConfirm"
      @cancel="clear"
      show-toolbar
    />
  </van-popup>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { getAllArea } from '@/api'
const emit = defineEmits(['confirm', 'canleCity'])
const Category: any = ref([])
const dataArr: any = ref([])
const idList: any = ref([])
const pickers = ref(null)
const props = defineProps({
  visibleCity: {
    type: Boolean,
    required: true,
    default: true
  }
})

const getAreaList = async () => {
  const res = await getAllArea()
  dataArr.value = res
  const itemArr: any = []
  const itemArrId: any = []
  dataArr.value.forEach((item: any) => {
    itemArr.push(item.name)
    itemArrId.push(item.id)
  })
  const ar:any = []
  dataArr.value[0].children.forEach((item: any) => {
    ar.push(item.name)
  })
  Category.value = [
    {
      values: itemArr,
      className: 'column1'
    },
    {
      values: ar,
      className: 'column2'
    }
  ]
}
getAreaList()

const onConfirm = async (list: any, index: any) => {
  idList.value = [dataArr.value[index[0]].id, dataArr.value[index[0]].children[index[1]].id]
  emit('confirm', list, idList.value)
  hide()
}

const onChange = async (picker: any, values: any, index: any) => {
  dataArr.value.forEach((i: any, v: any) => {
    if (i.name === picker[0]) {
      const newarr: any = []
      i.children.forEach((item: any) => {
        newarr.push(item.name)
      })
      pickers.value.setColumnValues(1, newarr)
    }
  })
}

const clear = async () => {
  const val = '请选择您的地址'
  const list:any = []
  emit('confirm', list, val)
  hide()
}

const hide = async () => {
  emit('canleCity', false)
}
</script>
